package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {



    @Autowired
    private RestHighLevelClient restHighLevelClient;


    @Override
    public PageResult search(RequestParams params) {

        try {
            SearchRequest request = new SearchRequest("hotel");

            SearchSourceBuilder source = request.source();

            buildBasicQuery(params,source);



            source.from((params.getPage() - 1) * params.getSize() );
            source.size(params.getSize());

            String location = params.getLocation();
            if (StringUtils.isNotBlank(location)){
                source.sort(SortBuilders.geoDistanceSort("location",new GeoPoint(location))
                                         .order(SortOrder.ASC)
                                          .unit(DistanceUnit.KILOMETERS)
                );
            }


            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);

            SearchHits hits = response.getHits();
            PageResult pageResult = new PageResult();

            pageResult.setTotal(hits.getTotalHits().value);
            List<HotelDoc> list = new ArrayList<>();

            for (SearchHit hit : hits) {
                HotelDoc hotelDoc = JSON.parseObject(hit.getSourceAsString(),HotelDoc.class);

                if (StringUtils.isNotBlank(location)){
                    Object[] sortValues = hit.getSortValues();
                    if (sortValues != null && sortValues.length > 0){
                        hotelDoc.setDistance(sortValues[0]);
                    }
                }



                list.add(hotelDoc);
            }

            pageResult.setHotels(list);
            return  pageResult;
        } catch (IOException e) {
            e.printStackTrace();
            throw  new RuntimeException("es搜索错误");
        }

    }

    @Override
    public Map<String, List<String>> getFilters(RequestParams params) {
        try {
            SearchRequest request = new SearchRequest("hotel");
            SearchSourceBuilder source = request.source();

            buildBasicQuery(params,source);

            source.size(0);

            buildAggregations(source);

            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);

            Aggregations aggregations = response.getAggregations();
            List<String> brandList = getAggByName(aggregations,"brandAgg");
            List<String> cityList = getAggByName(aggregations,"cityAgg");
            List<String> starNameList = getAggByName(aggregations,"starNameAgg");

            Map<String,List<String>> map = new HashMap<>();
            map.put("brand",brandList);
            map.put("city",cityList);
            map.put("starName",starNameList);
            return map;
        } catch (IOException e) {
            e.printStackTrace();
            throw  new RuntimeException("聚合查询失败");
        }
    }

    @Override
    public List<String> suggestion(String key) {

        try {
            SearchRequest request = new SearchRequest("hotel");
            SearchSourceBuilder source = request.source();

            source.suggest(
                    new SuggestBuilder()
                    .addSuggestion("mySuggestion",
                            SuggestBuilders.completionSuggestion("suggestion")
                    .prefix(key)
                    .skipDuplicates(true)
                    .size(10)
                    )
            );
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);

            Suggest suggest = response.getSuggest();

            CompletionSuggestion suggestion = suggest.getSuggestion("mySuggestion");

            List<CompletionSuggestion.Entry.Option> options = suggestion.getOptions();

            List<String> suggestionList = new ArrayList<>();

            for (CompletionSuggestion.Entry.Option option : options) {
                suggestionList.add(option.getText().toString());
            }
            return  suggestionList;

        } catch (IOException e) {
            e.printStackTrace();
            throw  new RuntimeException("自动不全失败");
        }

    }

    @Override
    public void deleteById(Long id) {
        try {
            // 1.准备Request
            DeleteRequest request = new DeleteRequest("hotel", id.toString());
            // 2.发送请求
            restHighLevelClient.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void insertById(Long id) {
        try {
            // 0.根据id查询酒店数据
            Hotel hotel = getById(id);
            // 转换为文档类型
            HotelDoc hotelDoc = new HotelDoc(hotel);
            // 1.准备Request对象
            IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());
            // 2.准备Json文档
            request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
            // 3.发送请求
            restHighLevelClient.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private List<String> getAggByName(Aggregations aggregations, String aggName) {

        Terms aggResult = aggregations.get(aggName);

        List<? extends Terms.Bucket> buckets = aggResult.getBuckets();

        List<String> resultList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            resultList.add(bucket.getKeyAsString());
        }
        return resultList;

    }

    private void buildAggregations(SearchSourceBuilder source) {
        source.aggregation(
                AggregationBuilders.terms("brandAgg")
                        .field("brand")
                        .size(20)
        );
        source.aggregation(
                AggregationBuilders.terms("cityAgg")
                        .field("city")
                        .size(20)
        );
        source.aggregation(
                AggregationBuilders.terms("starNameAgg")
                        .field("starName")
                        .size(20)
        );
    }


    private void buildBasicQuery(RequestParams params, SearchSourceBuilder source) {

        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();


        if (StringUtils.isAllBlank(params.getKey())){

            boolQuery.must(QueryBuilders.matchAllQuery());
        }else{
            boolQuery.must(QueryBuilders.matchQuery("all",params.getKey()));
        }

        String city = params.getCity();
        if (StringUtils.isNoneBlank(city)){
            boolQuery.filter(QueryBuilders.termQuery("city",city));
        }

        String brand = params.getBrand();
        if (StringUtils.isNoneBlank(brand)){
            boolQuery.filter(QueryBuilders.termQuery("brand",brand));
        }

        String starName = params.getStarName();
        if (StringUtils.isNoneBlank(starName)){
            boolQuery.filter(QueryBuilders.termQuery("starName",starName));
        }

        Integer minPrice = params.getMinPrice();
        Integer maxPrice = params.getMaxPrice();
         if (minPrice != null && maxPrice != null){
             boolQuery.filter(QueryBuilders.rangeQuery("price").gte(minPrice).lt(maxPrice));
         }

        FunctionScoreQueryBuilder functionScoreQueryBuilder =
                QueryBuilders.functionScoreQuery(
                        boolQuery,new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                        QueryBuilders.termQuery("isAD",true),
                                        ScoreFunctionBuilders.weightFactorFunction(10)
                                )
                        }
                ).boostMode(CombineFunction.MULTIPLY);
        source.query(boolQuery);
    }
}
